package com.nowcoder.community.controller.interceptor;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.util.HostHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //handler为拦截目标
        //判断拦截目标是否为方法，为方法才进行处理,instanceof，用于检查一个对象是否是某个类的实例或者是其子类的实例
        if(handler instanceof HandlerMethod){
            //强制转化为 HandlerMethod对象，从而方便调用其方法
            HandlerMethod handlerMethod =(HandlerMethod) handler;
            //获取拦截的方法对象
            Method method = handlerMethod.getMethod();
            //获取该方法的指定注解
            LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
            //异常排除：注解空值  用户是否登陆
            if(loginRequired != null && hostHolder.getUser()== null){
                //注解存在，且用户没登陆，拒绝访问，重定向回首页
                //使用respinse重定向
                response.sendRedirect(request.getContextPath()+"/login");
                return false;
            }

        }

        return true;
    }
}
